package main

import (
	"encoding/json"
	"fmt"
	"net/http"
	"strings"
	"time"

	"github.com/Fromsko/gouitls/knet"
	"github.com/tdewolff/parse/v2/buffer"
	"github.com/tidwall/gjson"
)

type Card struct {
	ID      string `json:"id"`
	Content string `json:"content"`
}

type NoteCard struct {
	ID           string `json:"setId"`
	URL          string `json:"-"`
	CSRF         string `json:"-"`
	Cards        []Card `json:"cards"`
	Title        string `json:"title"`
	Length       int    `json:"len"`
	PhotoURL     string `json:"photo"`
	PhotoBaseURL string `json:"-"`
}

func GetNoteCard(noteCard *NoteCard) error {

	data := (func() *buffer.Reader {
		d, _ := json.Marshal(map[string]interface{}{
			"setId": noteCard.ID,
			"_req":  time.Now().Unix(),
		})
		return buffer.NewReader(d)
	})()

	sendRequest := knet.SendRequest{
		FetchURL: noteCard.URL,
		Method:   "POST",
		Headers: map[string]string{
			"authority":          "qingk.com",
			"accept":             "application/json, text/plain, */*",
			"accept-language":    "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
			"cache-control":      "no-cache",
			"content-type":       "application/json",
			"expires":            "0",
			"origin":             "https://qingk.com",
			"platform":           "web_pc",
			"pragma":             "no-cache",
			"sec-ch-ua":          "\"Not A(Brand\";v=\"99\", \"Microsoft Edge\";v=\"121\", \"Chromium\";v=\"121\"",
			"sec-ch-ua-mobile":   "?0",
			"sec-ch-ua-platform": "\"Windows\"",
			"sec-fetch-dest":     "empty",
			"sec-fetch-mode":     "cors",
			"sec-fetch-site":     "same-origin",
			"user-agent":         "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36 Edg/121.0.0.0",
		},
		Cookies: []*http.Cookie{
			{
				Name:  "csrfToken",
				Value: noteCard.CSRF,
			},
		},
		Data: data,
	}

	sendRequest.Send(func(resp []byte, cookies []*http.Cookie, err error) {

		respJSON := gjson.ParseBytes(resp)

		if respJSON.Get("code").Int() == 0 {
			result := respJSON.Get("result")

			if result.Get("cards").IsArray() {
				cards := make([]Card, 0)

				result.Get("cards").ForEach(func(key, value gjson.Result) bool {
					card := Card{
						ID:      value.Get("id").String(),
						Content: gjson.Get(value.Get("frontContent").String(), "0.insert").String(),
					}

					cards = append(cards, card)

					return true
				})

				noteCard.Cards = cards
			}

			cardSet := result.Get("cardSet")
			noteCard.Title = cardSet.Get("title").String()
			noteCard.Length = len(strings.Split(cardSet.Get("children").String(), ","))

			author := result.Get("author")
			noteCard.PhotoURL = noteCard.PhotoBaseURL + author.Get("photo").String()
		}
	})

	return nil
}

func main() {
	noteCard := NoteCard{
		ID:           "DHTFdld1OURm",
		URL:          "https://qingk.com/api/dataview/open-data",
		PhotoBaseURL: "https://cdn.qingk.com/avatar/",
		// CSRF: "WPYjGhBITG3oUFp7Wa1tmiVl",
	}

	err := GetNoteCard(&noteCard)
	if err != nil {
		fmt.Println("Error:", err)
		return
	}

	fmt.Printf("%+v", noteCard)
}
